package com.acme.bankapp.service.bank.network;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.client.Client;
import com.acme.bankapp.service.bank.network.command.AddClientCommand;
import com.acme.bankapp.service.bank.network.command.Command;
import com.acme.bankapp.service.bank.network.command.InvalidCommand;
import com.acme.bankapp.service.bank.network.command.PrintBalanceCommand;
import com.acme.bankapp.service.bank.utils.ClientFactory;
import com.acme.bankapp.service.bank.utils.ClientInfoParser;
import com.acme.bankapp.service.bank.utils.ParseClientInfoException;

/**
 * This class process request message and get {@link Command} object to execute
 *
 * @author Alexander Kotov (kotov.alex.22@gmail.com)
 */
public class BankRequestProcessor {
    private final int FEED_BEGIN_INDEX = 4;
    private Bank bank;

    public BankRequestProcessor(final Bank bank) {
        this.bank = bank;
    }

    /**
     * @param request input message
     * @return {@link Command} object to execute
     */
    public Command process(final String request) {
        if (request.startsWith("add ")) {
            try {
                Client client = ClientFactory.createClient(new ClientInfoParser(request.substring(FEED_BEGIN_INDEX)));
                return new AddClientCommand(bank, client);
            } catch (ParseClientInfoException e) {
                return new InvalidCommand(e.getMessage());
            }
        } else if ("info".equals(request)) {
            return new PrintBalanceCommand(bank);
        } else {
            return new InvalidCommand(String.format("Invalid command: '%s'", request));
        }
    }
}
